package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult saveWmUser(WmUser wmUser) {
        wmUser.setCreatedTime(new Date());
        this.save(wmUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public WmUser findByName(String name) {
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName,name);
        List<WmUser> wmUsers = wmUserMapper.selectList(queryWrapper);
        if (wmUsers.size()>0){
            return wmUsers.get(0);
        }
        return null;
    }

    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.校验参数
        if (StringUtils.isEmpty(dto.getName())  || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名和密码不能为空");
        }
        //2.数据库查询是否合法
        Wrapper wrapper = new QueryWrapper<>();
        ((QueryWrapper) wrapper).eq("name",dto.getName());
        List<WmUser> userList = this.list(wrapper); //查询用户信息
        if (userList!=null && userList.size()==1){
            WmUser wmUser = userList.get(0);
            //根据查询的用户密码+库中的盐值 生成一个新的加密密码串,比较
            String salt = wmUser.getSalt();
            String pwdsqlt = dto.getPassword()+salt;
            String newpwd = DigestUtils.md5DigestAsHex(pwdsqlt.getBytes());
            if (newpwd.equals(wmUser.getPassword())){
                //用户输入的密码是对的  //3.生成token
                HashMap<Object, Object> hashMap = new HashMap<>();
                wmUser.setPassword("");
                wmUser.setSalt("");
                hashMap.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
                hashMap.put("user",wmUser);
                //4.把token,返回前端
                return ResponseResult.okResult(hashMap);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

}
